package epam.marchenko.library.services;

import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import epam.marchenko.library.domain.IncomeRecord;
import epam.marchenko.library.repository.IncomeRecordRepository;

@Service
public class IncomeRecordServiceImpl implements IncomeRecordService {

	@Autowired
	IncomeRecordRepository incomeRep;

	public void addIncomeRecord(IncomeRecord record) {
		incomeRep.create(record);
	}

	public List<IncomeRecord> getAllIncomeRecords() {
		return incomeRep.findAll();
	}

	public IncomeRecord find(IncomeRecord record) {
		return incomeRep.find(record);
	}
	
	public void deleteIncomeRecordById(int id) {
		incomeRep.deleteById(id);
	}

	public int getDelayDays(IncomeRecord record) {
		Date rrd = record.getRealReturnDate();
		Date rd = record.getOutcome().getReturnDate();
		int days = Days.daysBetween(new DateTime(rd), new DateTime(rrd))
				.getDays();
		return (days>0)?days:0;
	}

	public double countDelayFine(IncomeRecord record) {
		final double delayFineMult = 2;
		int delay = getDelayDays(record);
		double delayFine = record.getOutcome().getBook().getBookClass()
				.getRent()
				* delayFineMult * delay;
		record.setDelayFine(delayFine);
		incomeRep.update(record);
		return delayFine;
	}
}
